package com.xinchao.ck_mips.presenter;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.xinchao.ck_mips.App;
import com.xinchao.ck_mips.BuildConfig;
import com.xinchao.ck_mips.base.CKSubscriber;
import com.xinchao.ck_mips.base.MyBasePresenter;
import com.xinchao.ck_mips.constant.CK;
import com.xinchao.ck_mips.impl.BindModelImpl;
import com.xinchao.ck_mips.model.IBindModel;
import com.xinchao.ck_mips.utils.DeviceInfoUtil;
import com.xinchao.ck_mips.utils.DeviceUtil;
import com.xinchao.ck_mips.utils.NetWorkUtil;
import com.xinchao.ck_mips.utils.ShareUtil;
import com.xinchao.ck_mips.utils.ZXingUtils;
import com.xinchao.ck_mips.view.IBindView;
import com.xinchao.devicemanage.DeviceManager;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wq on 2019/4/23.
 */
public class BindPresenter extends MyBasePresenter<IBindView> {
    IBindModel mIRegisterModel = new BindModelImpl();
    private boolean isSuccess;

    private IBindModel getIBindModel() {
        if (mIRegisterModel == null) {
            mIRegisterModel = new BindModelImpl();
        }

        return mIRegisterModel;
    }

    /**
     * 绑定设备
     */
    public void bindDevice(boolean flag) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIBindModel().bind(getView().getEditText(), new IBindModel.IBindCallbackListener() {
            @Override
            public void onSuccessed(Object o) {
                getView().hideLoading();
                //绑定成功，调用注册接口
                register(false);
            }

            @Override
            public void onError(Throwable r) {
                getView().hideLoading();
                if (flag) {
                    if (!TextUtils.isEmpty(r.getMessage()) && r.getMessage().contains("-101")) {
                        getView().setErrorText(true, r.getMessage().replace("-101", ""));
                    }
                }
            }

            @Override
            public void onCompleted() {
                getView().hideLoading();
            }

            @Override
            public void onStart() {
                if (flag) {
                    getView().showLoading();
                }
            }
        });
    }

    /**
     * 轮询，二维码扫描没有回调，需要间隔请求接口查询
     * 15s请求一次
     */
    public void repeatRegister() {
        Flowable.timer(15, TimeUnit.SECONDS, Schedulers.io()).subscribe(new CKSubscriber<Long>(getView().getDisposable()) {
            @Override
            protected void next(Long aLong) {
                register(false);
            }

            @Override
            protected void finish() {
                if (!isSuccess) {
                    //结束轮询
                    repeatRegister();
                }
            }
        });

        /*Flowable.interval(15, TimeUnit.SECONDS, Schedulers.io()).subscribe(new CKSubscriber<Long>(getView().getDisposable()) {
            @Override
            protected void next(Long aLong) {
                if (isSuccess) {
                    //结束轮询
                    dispose();
                } else {
                    register(false);
                }
            }
        });*/
    }

    /**
     * 赋值二维码
     */
    public void setBtp() {
        try {
            if (DeviceManager.iBaseMachine == null) {
                DeviceManager.iBaseMachine = App.iBaseMachine;
            }
            Bitmap btp = ZXingUtils.createQRImage(BuildConfig.BAR_CODE_URL + DeviceInfoUtil.getInstance().getDeviceCode() + "&uniqueDeviceCode=" + DeviceManager.iBaseMachine.getUniqueDeviceCode(), 240, 240);
            getView().setZxingBtp(btp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册
     */
    public void register(boolean isShow) {
        getIBindModel().register("", DeviceUtil.getIP(getView().getContext()), DeviceUtil.getBootTime()
                , new IBindModel.IRegisterCallbackListener() {
                    @Override
                    public void onSuccessed(String t) {
                        //保存token
                        isSuccess = true;
                        ShareUtil.getInstance().putToken(t);
                        getView().gotoPlay();
                    }

                    @Override
                    public void onError(Throwable r) {
                        Logger.t(CK.TAG).e(r.getMessage());
                        isSuccess = false;
                        try {
                            if (!TextUtils.isEmpty(r.getMessage())) {
                                if (r.getMessage().contains("-100")) {
                                    //非法设备，先绑定
                                    getView().setErrorText(false, "请先绑定设备");
                                    bindDevice(false);
                                } else if (r.getMessage().contains("-102")) {
                                    getView().setErrorText(false, "设备注册中...");
                                    register(false);
                                } else if (r.getMessage().contains("-103")) {
                                    getView().setErrorText(false, "请联系管理人员解绑");
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }
                });
    }

}
